package com.example.lib_base.base.network.interecpter;


import com.example.lib_base.base.utils.MyLogUtil;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author yedong
 * @date 2019/1/15
 */

public class LogInterceptor implements Interceptor {


    public static final String TAG = "LogInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        MyLogUtil.v("HttpWatcher", url);
        //为了方便，将POST请求体参数也拼到url后面打印出来
        StringBuilder fullUrl = new StringBuilder();
        fullUrl.append(url).append("?");
        //为了打印POST的表单请求参数
        RequestBody requestBody = request.body();
        if (requestBody instanceof FormBody) {
            StringBuilder sb = new StringBuilder();
            FormBody formBody = (FormBody) requestBody;
            int size = formBody.size();
            for (int i = 0; i < size; i++) {
                String name = formBody.encodedName(i);
                String value = formBody.encodedValue(i);
                fullUrl.append(name).append("=").append(value);
                if (i < size - 1) {
                    fullUrl.append("&");
                }
                sb.append(name + "=" + value + ",");
            }
            sb.delete(sb.length() - 1, sb.length());
            MyLogUtil.v("HttpWatcher", "| RequestParams:{" + sb.toString() + "}");
            MyLogUtil.d("HttpWatcher", fullUrl.toString());
        }

        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        okhttp3.MediaType mediaType = responseBody.contentType();
        String content = responseBody.string();

        if (responseBody == null) {
            MyLogUtil.d("HttpWatcher", "返回结果为空");
        } else {
            MyLogUtil.d("HttpWatcher", content);
        }
        return response
                .newBuilder()
                .body(ResponseBody.create(mediaType, content))
                .build();
    }
}
